package com.ruoyi.framework.multiTenant;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;

@Component
public class TenantContextFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            // 从登录用户中获取学院ID
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null && loginUser.getUser() != null) {
                Integer collegeId = loginUser.getCollegeId();
                System.out.println("Filter中获取到学院ID: " + collegeId);

                if (collegeId != null) {
                    CollegeTenantContext.setCollegeId(collegeId);
                    System.out.println("设置当前线程collegeId: " + collegeId);
                } else {
                    System.out.println("警告：当前用户学院ID为空");
                    // 可以设置一个默认值
                    CollegeTenantContext.setCollegeId(1); // 设置默认值
                }
            } else {
                System.out.println("当前无登录用户，不设置租户ID");
            }
        } catch (Exception e) {
            // 捕获异常但不中断请求
            System.out.println("获取登录用户信息失败，可能未登录: " + e.getMessage());
        }

        try {
            chain.doFilter(request, response);
        } finally {
            CollegeTenantContext.clear();
            System.out.println("清除当前线程collegeId");
        }
    }
}
